package ie.dpsystems.errorlog;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends Activity implements IErrorListView {

	private ErrorListController _controller;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		_controller = new ErrorListController(this);
		_controller.CalculateErrorList();
		_receiver = new SyncFinishedBroadcastReceiver(){

			@Override
			public void ProcessBroadcast() {
				// TODO Auto-generated method stub
				MainActivity.this._controller.CalculateErrorList();
			}
			
		};
		_intentFilter = new IntentFilter(SyncService.ActionName);		
		AlarmConfiguration.StartAlarm(this);
		
	}
	private SyncFinishedBroadcastReceiver _receiver;
	private IntentFilter _intentFilter;
	
	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(_receiver, _intentFilter);
		TriggerSync();
		
	}
	@Override
	protected void onPause(){
		super.onPause();
		unregisterReceiver(_receiver);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		menu.add("Sync");		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case 0:
			TriggerSync();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	private void TriggerSync() {
		Intent msgIntent = new Intent(this, SyncService.class);	        	
		startService(msgIntent);
	}
	

	
	
	@Override
	public void SetErrorList(final List<ErrorBasicDetails> list) {
		// TODO Auto-generated method stub
		ListView currentErrorList = (ListView) findViewById(R.id.listViewBasicErrorDetails);
		BasicErrorDetailListAdapter adapter = new BasicErrorDetailListAdapter(this, list);
		currentErrorList.setAdapter(adapter);
		currentErrorList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				int uniqueId = list.get(index).get_serverUniqueId();
				Log.i("tag",Integer.toString(index));
				Intent intent = new Intent(MainActivity.this.getBaseContext(), ErrorDetailsActivity.class);
				intent.putExtra("errorUniqueId", uniqueId);
				MainActivity.this.startActivity(intent);
				
			}
		});
	}
	


}
